<?php
namespace app\controllers;

use app\models\UserOld;
use Yii;
use curl;
use tools;
use app\models\CooperateApp;
use yii\rest\ActiveController;
use yii\web\User;

//use app\models\OauthAccessToken;

class WechatController extends ActiveController
{

    public $app_id;
    public $toosClass;
    public $curlClass;
    public $access_token;
    public $rUrl;
    public $wechatAppId;
    public $wechatAppSecret;
    public $appid;
    public $appsecret;
    public $modelClass = 'app\models\User';

    public function actions ()
    {
        $actions = parent::actions ();
        unset($actions['index'] , $actions['update'] , $actions['create'] , $actions['delete'] , $actions['view']);
        return $actions;
    }

    public function beforeAction ( $action )
    {
        $this->toosClass = new tools();
        $this->curlClass = $curlClass = new curl();
         
        $this->access_token = Yii::$app->request->get ( 'access_token' );
        $this->rUrl = urldecode ( Yii::$app->request->get ( 'r' ) );

            $this->appid=Yii::$app->redis->get('wechat:appid');
            $this->appsecret=Yii::$app->redis->get('wechat:appsecret');
            return $this->appid;
//        }
    }


    /**
     * 微信授权
     * @author LiShaoWei
     * @access public
     * @param mixed $cooperate_app_id 用户id
     * @param mixed $r 回调地址
     * @since 1.0
     * @return array
     */
    public function actionOauth ()
    {
//        $wechatUrl = urlencode ( Yii::$app->request->hostInfo . "/wechat/connect?r=" . $this->rUrl );
         $wechatUrl = 'http://hebao.vguang.com/wechat/connect';
         $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=" . $wechatUrl . "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
         $this->redirect($url);
    }

    /**
     * 微信授权snsapi_base
     * @author LiShaoWei
     * @access public
     * @param mixed $cooperate_app_id 用户id
     * @param mixed $code 微信code
     * @param mixed $r 回调地址
     * @since 1.0
     * @return array
     */
    public function actionConnect ()
    {
        $cooperateAppId = Yii::$app->request->get ( 'cooperate_app_id' );
        $code = Yii::$app->request->get ( 'code' );
        //调用去验证
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=" .$code. "&grant_type=authorization_code";


        //$user=;
        $user=json_decode(file_get_contents($url),true);
        if($model=Yii::$app->redis->hgetall('user:id:'.$user['openid']))
        {
            echo 1;
            var_dump($model);die();
        }
        $wechatUserUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $user['access_token'] . "&openid=" . $user['openid'] . "&lang=zh_CN";
        $wechatUserGet = json_decode ( file_get_contents ( $wechatUserUrl ) , true );
        Yii::$app->redis->hmset("user:id:".$wechatUserGet['openid'],
                      'nickname', $wechatUserGet['nickname'],
                      'sex', $wechatUserGet['sex'],
                      'city', $wechatUserGet['city'],
                      'province', $wechatUserGet['province'],
                      'country', $wechatUserGet['country'],
                      'headimgurl', $wechatUserGet['headimgurl']
        );
        echo $wechatUserGet['openid'];
    }


    public function actionMenuCreate()
    {
//        $cooperateAppId ,
//        $dataPost['name'] ,
//        $dataPost['target_type'] ,
//        $dataPost['target_cont'] ,
//        $this->app_id ,
//        $dataPost['parent_id'];
        $dataPost= Yii::$app->request->post ();
        $dataPost['name']='测试';
        $dataPost['target_type']='测试';
        $dataPost['target_cont']='view';
        $dataPost['parent_id']='2';
       // echo $id=Yii::$app->redis->incr('id');
//        Yii::$app->redis->hmset("wechat:menu:id:".$id,
//                                'name',$dataPost['name'],
//                                'target_type',$dataPost['target_type'],
//                                'target_cont',$dataPost['target_cont'],
//                                'parent_id',$dataPost['parent_id']?$dataPost['parent_id']:0
//        );
        var_dump(Yii::$app->redis->hgetall('wechat:menu:id:1'));
        var_dump(Yii::$app->redis->hgetall('wechat:menu:id:2'));
    }

    public function actionAccessToken()
    {

        if($model=Yii::$app->redis->get('access_token'))
        {
            echo $model;
        }else{
            $accesstokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;
            $access_token = json_decode ( file_get_contents ( $accesstokenurl ) );
            if (isset($access_token->errcode)) {
                return array ( '500' , '获取aaccess_token微信错误' );
            }
            Yii::$app->redis->set('access_token',$access_token->access_token,'ex',$access_token->expires_in);
            echo Yii::$app->redis->get('access_token');
        }
    }

    public function actionTest()
    {
        $userModel=new \app\models\User();
        $userOldModel=new UserOld();
        $model=$userModel->find()->asArray()->all();
        foreach($model as $k=>$v)
        {
            $userOldModel::find()->createCommand()->update('user_old',['new_user_id'=>$v['id'],'open_id'=>$v['open_id']],
                ['portrait'=>$v['portrait']])->execute();
        }
    }


}